package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static com.example.demo.common.RabbitMqConst.*;

/**
 * @author FKJGFK
 * @version 1.0.0
 * @ClassName SendMsgController.java
 * @Description 消息发送接口
 * @createTime 2021/04/09 10:49:36
 */
@RestController
public class SendMsgController {

	@Autowired
	private RabbitTemplate rabbitTemplate;  //使用RabbitTemplate,这提供了接收/发送等等方法

	@GetMapping("/sendDirectMsg")
	public String sendDirectMsg() {
		String msgId = UUID.randomUUID().toString();
		String msgData = "sendDirectMsg!";
		String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

		Map<String, Object> map = new HashMap<>(3);
		map.put("msgId", msgId);
		map.put("msgData", msgData);
		map.put("createTime", createTime);

		//将消息携带绑定键值：TestDirectRouting 发送到交换机TestDirectExchange
		rabbitTemplate.convertAndSend(TEST_DIRECT_EXCHANGE, TEST_DIRECT_ROUTING, JSON.toJSONString(map));
		return "ok";
	}

	@GetMapping("/sendTopicMsg1")
	public String sendTopicMsg1() {
		String msgId = UUID.randomUUID().toString();
		String msgData = "sendTopicMsg1!";
		String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

		Map<String, Object> map = new HashMap<>(3);
		map.put("msgId", msgId);
		map.put("msgData", msgData);
		map.put("createTime", createTime);

		rabbitTemplate.convertAndSend(TEST_TOPIC_EXCHANGE, TEST_TOPIC_ROUTING_A, JSON.toJSONString(map));
		return "ok";
	}

	@GetMapping("/sendTopicMsg2")
	public String sendTopicMsg2() {
		String msgId = UUID.randomUUID().toString();
		String msgData = "sendTopicMsg2!";
		String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

		Map<String, Object> map = new HashMap<>(3);
		map.put("msgId", msgId);
		map.put("msgData", msgData);
		map.put("createTime", createTime);
		rabbitTemplate.convertAndSend(TEST_TOPIC_EXCHANGE, TEST_TOPIC_ROUTING_B, JSON.toJSONString(map));
		return "ok";
	}

}